package com.qifan.energy.util;

import android.content.Context;
import android.media.MediaPlayer;

import com.qifan.energy.R;

public class GameMusicBgUtil {

    public static boolean isPlaying = false;//是否正在播放

    private static GameMusicBgUtil musicBgUtil;

    // 声明MediaPlayer对象
    private MediaPlayer mediaPlayer;

    //单例模式
    public static GameMusicBgUtil getInstance(Context context) {
        if (musicBgUtil == null){
            musicBgUtil = new GameMusicBgUtil(context);
        }
        return musicBgUtil;
    }

    private GameMusicBgUtil(Context context) {
        if (mediaPlayer == null){
            // 根据音乐资源文件创建MediaPlayer对象 设置循环播放属性 开始播放
            mediaPlayer = MediaPlayer.create(context.getApplicationContext(), R.raw.game_music_bg);
//            mediaPlayer.prepareAsync();
            mediaPlayer.setLooping(true);
        }
    }

    /* 播放音乐 */
    public void playMusic() {
        if (mediaPlayer != null && !mediaPlayer.isPlaying()){
            mediaPlayer.start();
            isPlaying = true;
        }
    }

    /* 暂停音乐 */
    public void pauseMusic() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()){
            mediaPlayer.pause();
            isPlaying = false;
        }
    }

    /* 关闭音乐 */
    public void stopMusic() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            isPlaying = false;
        }
    }
}
